import router, { resetRouter } from '@/router'
import Api from '../api'
import workRouter from '@/router/work-router'
import { isArray } from 'lodash'

// 按钮权限列表
const btnRoleList = {}
/**
 * 递归过滤异步路由表
 * @param routes 后端返回的异步路由表
 * @param menus 前端所有的路由
 */
function filterAsyncRoutes(routes, menus) {
	const allRouter = []
	for (const i in menus) {
		// 循环所有路由
		const menu = menus[i]
		for (const j in routes) {
			// 循环后端有权限的路由
			const route = routes[j]
			if (menu.name === route.name || (menu.meta && menu.meta.active === route.name)) {
				if (menu.children && menu.children.length) {
					if (route.children && route.children.length) {
						menu.children = filterAsyncRoutes(route.children, menu.children)
					} else {
						menu.children = []
					}
				}
				if (menu.meta) {
					menu.meta.title = route.routeName || ''
					menu.meta.icon = route.icon || ''
				}

				if (route.buttons && isArray(route.buttons)) {
					btnRoleList[route.name] = route.buttons
				} else {
					throw new Error('后台菜单按钮返回格式应该为数组')
				}
				allRouter.push(menu)
			}
		}
	}
	return allRouter
}
// 过滤路由方法
function filter(arg) {
	const menu = JSON.parse(JSON.stringify(arg))
	const arr = []
	for (const i in menu) {
		if ((menu[i].meta && menu[i].name === menu[i].meta.active) || !menu[i].meta || !menu[i].meta.active) {
			if (menu[i].children && menu[i].children.length) {
				menu[i].children = filter(menu[i].children)
			}
			delete menu[i].component // 删除无用字段
			arr.push(menu[i])
		}
	}
	return arr
}
/**
 * 通过路由名称递归查找某个路由数据信息
 * @param routes 后端返回的异步路由表
 * @param menus 前端所有的路由
 */
function findSomeRouteByName(menus, name) {
	const menu = JSON.parse(JSON.stringify(menus))
	let obj = null
	for (const i in menu) {
		if (menu[i].name === name) {
			obj = menu[i]
		} else {
			if (menu[i].children && menu[i].children.length) {
				obj = findSomeRouteByName(menu[i].children, name)
			}
		}
	}
	return obj
}

const state = {
	menuRouter: [], // 菜单数据
	projectRouter: [], // 光明工程菜单数据，业务没有的话可以删除
	secondaryRouter: [], // 区项目详情
	btnRoleList: {} // 按钮权限列表
}

const mutations = {
	// 设置菜单路由
	SET_ROUTES: (state, routes) => {
		state.menuRouter = routes
	},
	SET_PROJECT_ROUTES: (state, routes) => {
		state.projectRouter = routes
	},
	SET_ROLELIST: (state, routes) => {
		state.btnRoleList = routes
	},
	SET_SECONDARY_ROUTE: (state, routes) => {
		state.secondaryRouter = routes
	}
}

const actions = {
	// 获取当前路由
	generateRoutes({ commit }) {
		return new Promise((resolve, reject) => {
			if ($config.needFeatchMenu) {
				Api.getMenus()
					.then(response => {
						// 从前端的全部业务路由里根据后端返回的路由过滤出有权限的路由
						const accessedRoutes = filterAsyncRoutes(response, workRouter)

						// 设置按钮权限以便指令使用
						commit('SET_ROLELIST', btnRoleList)

						// 补全路由
						let addRouter = []
						if (accessedRoutes.length) {
							// 是否有跟路由
							const hasRoot = accessedRoutes.find(item => item.path === '/')
							if (hasRoot) {
								addRouter = accessedRoutes
							} else {
								addRouter = [
									...accessedRoutes,
									{
										path: '/',
										redirect: accessedRoutes[0].path
									}
								]
							}
						} else {
							// 一个路由也没有，进403
							addRouter = [
								{
									path: '/',
									redirect: '/403'
								}
							]
						}

						// 保存菜单数据路由
						let menuRouter = [] // 菜单数据，用于侧边栏显示
						const menuRoute = accessedRoutes.find(item => item.name === 'index')
						if (menuRoute) {
							menuRouter = filter(menuRoute.children || [])
							commit('SET_ROUTES', menuRouter)
						}

						// 如果业务没有这块逻辑可以删除
						const project = accessedRoutes.find(item => item.name === 'project')
						if (project) {
							// 设置工程管家菜单数据
							const filterProject = filter(project.children || [])
							commit('SET_PROJECT_ROUTES', filterProject)

							console.log('project', project)
							// 设置二级路由区项目管理菜单数据
							const secondaryProject = findSomeRouteByName([project], 'secondaryProject')
							if (secondaryProject) {
								commit('SET_SECONDARY_ROUTE', filter(secondaryProject.children || []))
							}
						}

						console.log('保存路由完毕')

						// 重置路由
						resetRouter()
						// 赋值路由给变量
						// router.routesList = constantRoutes.concat(addRouter)
						// 动态添加路由
						addRouter.forEach(v => {
							router.addRoute(v) // 这里添加几个路由就会执行几次路由钩子
						})
						console.log('添加路由完毕')
						resolve(addRouter)
					})
					.catch(err => {
						reject(err)
					})
			} else {
				console.log('workRouter', workRouter)
				// const menuRoute = workRouter.find(item => {
				// 	console.log(item)
				// 	return item.component && item.component.name === 'containerLayout'
				// })

				const menuRoute = workRouter.find(item => item.name === 'index')
				if (menuRoute) {
					const menuRouter = filter(menuRoute.children || [])
					console.log('menuRouter', menuRouter)

					commit('SET_ROUTES', menuRouter)
				}
				// 如果业务没有这块逻辑可以删除
				const project = workRouter.find(item => item.name === 'project')
				if (project) {
					// 设置工程管家菜单数据
					const filterProject = filter(project.children || [])
					commit('SET_PROJECT_ROUTES', filterProject)

					console.log('project', project)
					// 设置二级路由区项目管理菜单数据
					const secondaryProject = findSomeRouteByName([project], 'secondaryProject')
					console.log(secondaryProject)
					if (secondaryProject) {
						console.log(filter(secondaryProject.children || []))

						commit('SET_SECONDARY_ROUTE', filter(secondaryProject.children || []))
					}
				}
				resolve()
			}
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
